package com.wanwucs.imagelibrary;

import android.graphics.Bitmap;
import android.graphics.Color;

import java.util.Random;

/**
 * Created by chenhaitao on 2017/8/3.
 */

public class ImageUtil {

    private static final String POINTS = ".,;'";
    private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String MARKS = "<>?-+";

    public static String image2Text(Bitmap bitmap){
        if (null == bitmap){
            return "";
        }
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int[] pixels = new int[width * height];
        bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
        StringBuilder sb = new StringBuilder();
        for (int i = 0;i<pixels.length;i++){
            int color = pixels[i];
            int a = Color.alpha(color);
            int r = Color.red(color);
            int g = Color.green(color);
            int b = Color.blue(color);
            float[] hsv = new float[3];
            Color.RGBToHSV(r, g, b, hsv);
            float sub = 1- hsv[2];
            if (sub>=0&&sub<0.05){
                sb.append(" ");
            }else if (sub>=0.05&&sub<0.3){
                sb.append(getRandonString(POINTS));
            } else if (sub>=0.3&&sub<0.5){
                sb.append(getRandonString(MARKS));
            } else  {
                sb.append(getRandonString(CHARS));
            }
            if ((i+1) % bitmap.getWidth()==0){
                sb.append("\n");
            }
        }
        return sb.toString();

    }


    private static String getRandonString(String chars){
        boolean[] bools = new boolean[chars.length()];
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        int i = random.nextInt(chars.length());
        for(int j=0;j<2;j++){
            while(bools[i]){
                i = random.nextInt(chars.length());
            }
            bools[i] = true;
            sb.append(chars.charAt(i));
        }
        return sb.toString();
    }


}
